package com.lujieni.springbootsecurity.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lujieni.springbootsecurity.dao.UserMapper;
import com.lujieni.springbootsecurity.po.UserDO;
import com.lujieni.springbootsecurity.utils.JWTUtils;
import com.lujieni.springbootsecurity.utils.SecurityFrameworkUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/5/29 14:32
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class LoginService {

    private final JWTUtils jwtUtils;

    private final UserMapper userMapper;

    private final RedisTemplate<String, String> redisTemplate;

    private static final String REDIS_TOKEN_KEY = "login-token:%s:%s";

    public String login(String username, String password){
        UserDO sysUserDO = new UserDO();
        sysUserDO.setUserName(username);
        sysUserDO.setPassword(password);
        UserDO user = userMapper.selectOne(new LambdaQueryWrapper<UserDO>().eq(UserDO::getUserName, username).eq(UserDO::getPassword, password));
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        String token = jwtUtils.generateRenewToken(String.valueOf(user.getId()));
        redisTemplate.opsForValue().set(String.format(REDIS_TOKEN_KEY, user.getId(), token), token, JWTUtils.TOKEN_EXPIRE_SECONDS, TimeUnit.SECONDS);
        return token;
    }

    public String hey(String username){
        return "hey success";
    }

    public void logout(HttpServletRequest request) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        redisTemplate.delete(String.format(REDIS_TOKEN_KEY, loginUserId, request.getHeader("token")));
    }


    /*
       private final AuthenticationManager authenticationManager;
        依赖AuthenticationManager进行用户的认证
        public String login(String username, String password){
            Authentication authenticate = null;
            authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
            LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
            return jwtUtils.generateRenewToken(String.valueOf(loginUser.getUserId()));
        }
    */

}
